import {
    globalTool
} from "./BQGIS-globalVar"

export function initManuallyRender(enabled = false) {
    if (!globalTool.manuallyRender) {
        globalTool.manuallyRender = new ManuallyRender(enabled)
    }
    return globalTool.manuallyRender
}

function ManuallyRender(enabled) {
    this.registered = false // 事件是否已经注册
    if (enabled) {
        this.open()
    } else {
        this.close()
    }
}

ManuallyRender.prototype.open = function (viewer = window.viewer) {
    const scene = viewer.scene
    scene.requestRenderMode = true
    scene.maximumRenderTimeChange = Infinity;
    if (!this.registered) {
        viewer.on([mars3d.EventType.cameraChanged, mars3d.EventType.click, mars3d.EventType.mouseMove, mars3d.EventType.mouseOver, mars3d.EventType.keydown, mars3d.EventType.removeLayer], () => {
            scene.requestRender();
        }).on(mars3d.EventType.addLayer, e => {
            scene.requestRender();
            e.layer.on(
                [
                    mars3d.EventType.show,
                    mars3d.EventType.hide,
                    mars3d.EventType.change
                ],
                e => {
                    scene.requestRender();
                }
            );
        })
        this.registered = true
    }
}

ManuallyRender.prototype.close = function (viewer = window.viewer) {
    const scene = viewer.scene
    scene.requestRenderMode = false
    scene.maximumRenderTimeChange = 0.0;
}


ManuallyRender.prototype.destroy = function () {
    this.registered = false
}

// 切换状态 true:手动渲染, false:自动渲染
export function setRequestRenderMode(enabled) {
    const scene = viewer.scene
    scene.requestRenderMode = enabled
    scene.maximumRenderTimeChange = enabled ? Infinity : 0.0
}